package com.joy.controller;

import com.joy.command.*;
import com.joy.common.UserRegistration;
import com.joy.mapper.UserMapper;
import com.joy.model.User;
import com.joy.vo.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import static com.joy.common.UserType.userDesToTypeMap;

/**
 * 用户相关接口
 */
@Controller
public class UserController {

    @GetMapping("/test11")
    @ResponseBody
    public String test11() {
        return "123";
    }

    @Resource
    private UserMapper userMapper;

//    @GetMapping("/getUser")
//    @ResponseBody
//    public MangerSystemResponse<User> getUser(){
//        User admin001 = userMapper.selectById(1L);
//        return new MangerSystemResponse<User>().doSuccess(admin001);
//    }

    /**
     * 用户注册调用接口
     */
    @PostMapping("/m2/5591894-5270100-default/244178694")
    @ResponseBody
    public RegisterVO registerPage(@RequestParam String apifoxApiId,
                                   @RequestBody RegisterCommand command) throws NoSuchAlgorithmException {
        User userFromDb = userMapper.selectByUserName(command.getUsername());
        // 账号已经存在，返回失败
        if (userFromDb != null) {
            return new RegisterVO(false, null, null);
        }
        // 账号密码或者用户名为空，返回失败
        if (StringUtils.isEmpty(command.getUsername()) || StringUtils.isEmpty(command.getPassword())) {
            return new RegisterVO(false, null, null);
        }
        // 用户不存在，新增账号
        //对密码进行加密操作
        String salt = UserRegistration.getSalt();
        String hashPassword = UserRegistration.hashPassword(command.getPassword(), salt);
        // 保存用户信息
        User user = new User();
        user.setUserName(command.getUsername());
        user.setSalt(salt);
        user.setPassword(hashPassword);
        user.setStatus(1);
        user.setType("2"); //默认创建的是学生
        userMapper.insert(user);// 插入数据库中
        return new RegisterVO(true, user.getId(), 2);
    }


    /**
     * 用户登录调用接口
     */
    @PostMapping("/m2/5591894-5270100-default/244177612")
    @ResponseBody
    public LoginVO login(@RequestParam String apifoxApiId,
                         @RequestBody LoginCommand command) throws NoSuchAlgorithmException {
        // 账号密码或者用户名为空，返回失败
        if (StringUtils.isEmpty(command.getUsername()) || StringUtils.isEmpty(command.getPassword())) {
            return new LoginVO(false, null, null);
        }
        // 根据用户名查询数据库中的记录
        User user = userMapper.selectByUserName(command.getUsername());
        if (user == null) {
            return new LoginVO(false, null, null);
        }
        // 密码核对
        if (!user.getPassword()
                .equals(UserRegistration.hashPassword(command.getPassword(), user.getSalt()))) {
            return new LoginVO(false, null, null);
        }
        return new LoginVO(true, user.getId(), user.getType());
    }

    /**
     * 用户信息查询接口
     */
    @PostMapping("/getUserInfo")
    @ResponseBody
    public UserInfoVO queryUserInfo(@RequestBody UserInfoQueryCommand command) {
        if (StringUtils.isEmpty(command.getId())) {
            return new UserInfoVO();
        }
        User user = userMapper.selectById(Long.valueOf(command.getId()));
        return UserInfoVO.from(user);
    }

    /**
     * 用户信息更新接口
     */
    @PostMapping("/m2/5591894-5270100-default/243073407")
    @ResponseBody
    public UserSaveVO saveUser(@RequestParam String apifoxApiId,
                               @RequestBody UserSaveCommand command) {
        User user = new User();
        user.setUserName(command.getName());
        user.setSchool(command.getSchool());
        user.setGender(command.getGender());
        userMapper.update(user);
        return new UserSaveVO(true);
    }

    @PostMapping("/m2/5591894-5270100-default/242716357")
    @ResponseBody
    public UpdatePasswordVO updatePassword(@RequestParam String apifoxApiId,
                                           @RequestBody UpdatePasswordCommand command) throws NoSuchAlgorithmException {
        // 账号密码或者用户名为空，返回失败
        if (StringUtils.isEmpty(command.getUsername()) || StringUtils.isEmpty(command.getPassword())) {
            return new UpdatePasswordVO(false);
        }
        User user = userMapper.selectByUserName(command.getUsername());
        if (user == null) {
            return new UpdatePasswordVO(false);
        }
        // 对新密码进行加密
        User newUser = new User();
        newUser.setUserName(user.getUserName());
        newUser.setPassword(UserRegistration.hashPassword(command.getPassword(), user.getSalt()));
        // 更新密码
        userMapper.update(newUser);
        return new UpdatePasswordVO(true);
    }

    /**
     * 用户信息查询接口
     */
    @GetMapping("/getAllUser")
    @ResponseBody
    public AllUserVO queryUserInfo() {
        List<User> users = userMapper.selectAll();
        ArrayList<UserInfoVO> userInfoVOS = new ArrayList<>();
        for (User user : users) {
            userInfoVOS.add(UserInfoVO.from(user));
        }
        return new AllUserVO(userInfoVOS);
    }

    /**
     * 用户信息修改接口
     */
    @PostMapping("/updateUserInfo")
    @ResponseBody
    public UpdateUserInfoVO updateUserInfo(@RequestBody UpdateUserInfoCommand command) {
        if (command.getId() == null) {
            List<User> users = userMapper.selectAll();
            ArrayList<UserInfoVO> userInfoVOS = new ArrayList<>();
            for (User user : users) {
                userInfoVOS.add(UserInfoVO.from(user));
            }
            return new UpdateUserInfoVO(false, userInfoVOS);
        }
        User user = new User();
        user.setId(command.getId());
        user.setPhone(command.getPhone());
        user.setUserName(command.getName());
        user.setType(userDesToTypeMap.getOrDefault(command.getType(), String.valueOf(1)));
        userMapper.update(user);
        return new UpdateUserInfoVO(true, getAllUserInfo());
    }

    /**
     * 用户信息新增接口
     */
    @PostMapping("/addUserInfo")
    @ResponseBody
    public AddUserInfoVO addUserInfo(@RequestBody AddUserInfoCommand command) throws NoSuchAlgorithmException {
        if (command.getId() == null || command.getName() == null) {
            return new AddUserInfoVO(false, getAllUserInfo());
        }
        // 区分唯一，系统里不能有id或者姓名相同的用户
        User userById = userMapper.selectById(command.getId());
        User userByName = userMapper.selectByUserName(command.getName());
        if (userById != null || userByName != null) {
            return new AddUserInfoVO(false, getAllUserInfo());
        }
        // 构建新用户信息
        User user = new User();
        user.setId(command.getId());
        user.setPhone(command.getPhone());
        user.setUserName(command.getName());
        user.setType(userDesToTypeMap.getOrDefault(command.getType(), String.valueOf(1)));
        //对密码进行加密操作,密码默认123456
        String salt = UserRegistration.getSalt();
        String hashPassword = UserRegistration.hashPassword("123456", salt);
        user.setSalt(salt);
        user.setPassword(hashPassword);
        user.setStatus(1);
        user.setGender("1");
        // 用户信息落表
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            return new AddUserInfoVO(false, getAllUserInfo());
        }
        return new AddUserInfoVO(true, getAllUserInfo());
    }

    /**
     * 用户信息删除接口
     */
    @PostMapping("/deleteUserInfo")
    @ResponseBody
    public DeleteUserInfoVO deleteUserInfo(@RequestBody DeleteUserInfoCommand command) {
        if (command.getId() == null) {
            return new DeleteUserInfoVO(false, getAllUserInfo());
        }
        userMapper.delete(command.getId());
        return new DeleteUserInfoVO(true, getAllUserInfo());
    }

    public List<UserInfoVO> getAllUserInfo() {
        List<User> users = userMapper.selectAll();
        ArrayList<UserInfoVO> userInfoVOS = new ArrayList<>();
        for (User user : users) {
            userInfoVOS.add(UserInfoVO.from(user));
        }
        return userInfoVOS;
    }

}
